package elitech.vietnam.weatherfashion.tabs.self;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.WarningDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.libs.multicolumlist.MultiColumnListView;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;

public class SelfChildFragment extends AbstractFragment implements OnRefreshListener2<MultiColumnListView> {

	private PullToRefreshGridView2 mGridView;
	private SelfGridAdapter mAdapter;

	String page = "";
	boolean isPullUp = false;
	List<PostDTO> data = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		page = getArguments().getString("page");
		View view = inflater.inflate(R.layout.self, null);
        setupView(view);

        mGridView = (PullToRefreshGridView2) view.findViewById(R.id.layout_main);
        
		return view;
	}
	
	@Override
	public void onPause() {
		super.onPause();
		mGridView.onRefreshComplete();
	}

	@Override
	public void onResume() {
		super.onResume();
		if ((page.equals(SelfFragment.TAB_MYSTYLE) && WFApplication.getInstance().selfData.isEmpty())
				|| (page.equals(SelfFragment.TAB_MYHEART) && WFApplication.getInstance().heartData.isEmpty())
				|| getActivity().getIntent().getIntExtra("SELF_RELOAD", -1) > 0)
			new SelfChildLoadingTask().execute();
		else
			loadData();
		getActivity().getIntent().removeExtra("SELF_RELOAD");
	}

	@Override
	public void onDestroyView() {
		mGridView = null;
//		mAdapter = null;
		super.onDestroyView();
	}

	private void loadData() {
		data = new ArrayList<PostDTO>();
		
		if (page.equals(SelfFragment.TAB_MYSTYLE))
			data.addAll(WFApplication.getInstance().selfData);
		
		if (page.equals(SelfFragment.TAB_MYHEART))
			data.addAll(WFApplication.getInstance().heartData);
		
		if (!data.isEmpty()) {
			onNoData(false);
			mGridView.setMode(Mode.PULL_FROM_END);
			mGridView.setOnRefreshListener(this);
			mAdapter = new SelfGridAdapter(SelfChildFragment.this, R.layout.styler_grid_item, data);
			mGridView.setAdapter(mAdapter);
			mAdapter.notifyDataSetChanged();
		}
		else
			onNoData(true);
	}

	class SelfChildLoadingTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				if (page.equals(SelfFragment.TAB_MYSTYLE))
					Utils.getSelfData(getActivity());
				if (page.equals(SelfFragment.TAB_MYHEART))
					Utils.getHeartData(getActivity());
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			onLoading(true);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			onLoading(false);
			if (result != null) {
				new WarningDialog.Builder(getActivity())
				.createTimeOutDialog().show();
				return;
			}
			loadData();
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}
	
	class LoadMoreItem extends AsyncTask<Integer, Integer, List<PostDTO>> {
		@Override
		protected List<PostDTO> doInBackground(Integer... params) {
			if (page == null)
				return null;
			if (!page.equals(SelfFragment.TAB_MYSTYLE) && !page.equals(SelfFragment.TAB_MYHEART))
				return null;
			boolean isAll = (page.equals(SelfFragment.TAB_MYSTYLE));
			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			int n = (user != null) ? user.getId() : -1;
			List<PostDTO> list = null;
			if (isAll) {
				try {
					list = service.getFashionMemberLikeCountry(n, n, Const.COUNTRY_CODE, data.size(), Const.LOADMORE_PAGE_ITEMCOUNT);
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			} else if (!isAll) {
				try {
					list = service.getPostLikeMember(n, Const.COUNTRY_CODE, data.size(), Const.LOADMORE_PAGE_ITEMCOUNT);
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
			return list;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(List<PostDTO> result) {
			super.onPostExecute(result);
			if (mGridView != null)
				mGridView.onRefreshComplete();
			if (result == null) {
				new WarningDialog.Builder(getActivity())
				.createTimeOutDialog().show();
				return;
			}
			if (result.isEmpty()) {
				if (mGridView != null) {
					mGridView.setMode(Mode.DISABLED);
					mGridView.setOnRefreshListener((OnRefreshListener2<MultiColumnListView>)null);
				}
				return;
			}
			if (data != null)
				data.addAll(result);
//			if (mAdapter != null)
//				mAdapter.notifyDataSetChanged();
		}
	}
}
